package pers.corvey.studyjava.util;

import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.groups.Default;

import pers.corvey.studyjava.model.form.MyValidatable;

public class ValidatorUtils {

    private static final Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
    
    public static String validate(MyValidatable obj) {
        Set<ConstraintViolation<MyValidatable>> set = validator.validate(obj, Default.class);
        if (set != null && set.size() > 0) {
            StringBuilder sb = new StringBuilder();
            for (ConstraintViolation<MyValidatable> cv : set) {
                sb.append(cv.getMessage());
                sb.append(", ");
            }
            int length = sb.length();
            sb.delete(length-2, length);
            return sb.toString();
        }
        return null;
    }
    
}
